using System;
using System.Collections.Generic;
using System.Linq;
using PhoneBook.Core.Data;
using PhoneBook.Core.Domain.Contacts;
using PhoneBook.Core.Domain.UserGroups;

namespace PhoneBook.Service.UserGroups
{
    public class UserGroupService : IUserGroupService
    {
        private IRepository<UserGroup> _userGroupRepository;
        private IRepository<Contact> _contactRepository;




        public UserGroupService(IRepository<UserGroup> userGroupRepository, IRepository<Contact> contactRepository)
        {
            _userGroupRepository = userGroupRepository;
            _contactRepository = contactRepository;
        }

        public IList<UserGroup> GetAllUserGroups()
        {
            return _userGroupRepository.Table.ToList();
        }

        public IList<UserGroup> GetAllUserGroupsByContact(int contactId)
        {
            var query = from ug in _userGroupRepository.Table
                        where ug.Contacts.Select(c => c.Id).Contains(contactId)
                        select ug;
            return query.ToList();

        }

        public void SaveUserGroupRelations(int contactId, IEnumerable<int> userGroupsIds)
        {

            //var contact = _contactRepository.GetById(contactId);
            //var userGroups = _userGroupRepository.Table.Where(c => userGroupsIds.Contains(c.Id)).ToList();


            //if (contact.UserGroups != null)
            //{
            //    contact.UserGroups.Clear();
            //}
            //else
            //{
            //    contact.UserGroups = new List<UserGroup>();
            //}

            //foreach (var ug in userGroups)
            //{
            //    contact.UserGroups.Add(ug);
            //}

            //_contactRepository.Update(contact);
        }

        public void AddUserGroup(UserGroup userGroup)
        {
            _userGroupRepository.Insert(userGroup);
        }
    }
}